package app.system.service.impl;

import app.system.entity.*;
import app.system.mapper.MusicMusicLisitMapper;
import app.system.mapper.SysMusicLikeMapper;
import app.system.mapper.SysMusicMapper;
import app.system.service.SysMusicService;
import app.utils.ImageToBase64;
import app.utils.Result.AjaxResult;
import app.utils.SoleID;
import app.utils.VeDate;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SysMusicServiceImpl implements SysMusicService {
    @Autowired
    private SysMusicMapper musicMapper;
    @Autowired
    private SysMusicLikeMapper musicLikeMapper;
    @Autowired
    private MusicMusicLisitMapper musicMusicLisitMapper;


    @Override
    public int saveMusic(SysMusic sysMusic) {
        return musicMapper.saveMusic(sysMusic);
    }

    @Override
    public PageInfo<SysMusic> getMusicAll(Page page) {
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        return new PageInfo<SysMusic>(musicMapper.getMusicAll());
    }

    @Override
    public List<SysMusic> getMusicAllList(){
        return musicMapper.getMusicAll();
    }

    @Override
    public List<SysMusic> selectMusicByTage(SysMusic sysMusic) {
        return musicMapper.selectMusicByTage(sysMusic);
    }


    /**
     * MultipartFile photoObj//若是本地图片则改为此对象
     * @param musicObj
     * @param parmMap
//     * @param photoObj
     * @param sysUser
     * @return
     */
    @Override
    public AjaxResult musicUpload(MultipartFile musicObj, Map<String, String> parmMap,SysUser sysUser) {
        //将文件写入服务器
        String MusicFilePath = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\MusicFile\\"+sysUser.getUser_name()+"\\";
        String MusicFileName = musicObj.getOriginalFilename();
        String musicSuffix  = MusicFileName.substring(MusicFileName.lastIndexOf(".")+1);
        SysMusic sysMusic = new SysMusic();
        File fileUpload = new File(MusicFilePath+MusicFileName);
        System.out.println("文件上传路径+++++++"+fileUpload);
        if (!fileUpload.exists()){
            fileUpload.mkdirs();
        }
        try {
            musicObj.transferTo(fileUpload);
            System.out.println("文件上传成功");
            //获取其余数据
            long fileL = musicObj.getSize();
            if (fileL/1048576>=1){
                int fileSize_M = (int)fileL/1048576;
                String fileSize = String.valueOf(fileSize_M)+"M";
                sysMusic.setMusic_size(fileSize);
            }else {
                int fileSize_K = (int) fileL/1024;
                String fileSize = String.valueOf(fileSize_K)+"K";
                sysMusic.setMusic_size(fileSize);
            }
            String music_path = "\\MusicFile\\"+sysUser.getUser_name()+"\\"+MusicFileName;
           sysMusic.setMusic_url(music_path);
            //将图片数据转化成base64编码，存入本地图片
//            sysMusic.setMusic_phoyourl(ImageToBase64.generateBase64(photoObj));
            //存入图片地址
            sysMusic.setMusic_phoyourl(parmMap.get("music_photourl"));
            String music_id = SoleID.getId();

            sysMusic.setMusic_name(MusicFileName.substring(0,MusicFileName.length()-musicSuffix.length()-1));
            sysMusic.setMusic_id(music_id);
            sysMusic.setMusic_note(parmMap.get("music_note"));
            sysMusic.setMusic_creatdate(VeDate.dateToStrLong(new Date()));
            sysMusic.setMusic_author(parmMap.get("music_author"));
            sysMusic.setMusic_type(parmMap.get("music_type"));
            sysMusic.setMusic_tage(parmMap.get("music_tage"));
            sysMusic.setMusic_uploadauthorid(sysUser.getUser_id());
            System.out.println(JSONObject.toJSONString(sysMusic));
            musicMapper.saveMusic(sysMusic);
            return AjaxResult.success("文件上传成功");
        }catch (IOException e){
//            LOGGER.error(file.getOriginalFilename()+"文件上传失败",e);
            System.out.println(musicObj.getOriginalFilename()+"文件上传失败"+e);
            return AjaxResult.error(-1,"文件上传失败");
        }
    }


    @Override
    public AjaxResult musicDownLoad(HttpServletResponse response, SysMusic sysMusic) {
        //先根据音乐文件id更新音乐的下载量
        SysMusicLike musicLike = new SysMusicLike();
        musicLike.setMusic_id(sysMusic.getMusic_id());
        List<SysMusicLike> musicLikeList = musicLikeMapper.selectMusicLikeByTage(musicLike);
        if (musicLikeList.size()<1){
            //说明音乐受喜欢程度表里还没此条数据，需要写入
            musicLike.setMusic_download(1);
            musicLikeMapper.saveMusicLike(musicLike);
        }else {
            musicLike.setMusic_download(musicLikeList.get(0).getMusic_download()+1);
            musicLikeMapper.updateMusicLikeByTage(musicLike);
        }

        SysMusic sysMusic1 = musicMapper.selectMusicByTage(sysMusic).get(0);
        String musicPath = sysMusic1.getMusic_url();
        System.out.println("音乐所在路径："+musicPath);
        File packetFile = new File(musicPath);
        String musicName = packetFile.getName(); //下载的文件名
        System.out.println("下载的文件名："+musicName);
        File file = new File(musicPath);
        // 如果文件名存在，则进行下载
            //配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(musicName, "UTF-8"));
            }catch (UnsupportedEncodingException e){
                System.out.println("文件名编码错误"+e);
            }
            // 实现文件下载
            FileInputStream fileInputStream = null;
            BufferedInputStream bufferedInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
                bufferedInputStream = new BufferedInputStream(fileInputStream);
                byte[] buffer = new byte[fileInputStream.available()];
                response.setHeader("Content-Lenth",""+buffer.length);
                OutputStream os = response.getOutputStream();
                int i = bufferedInputStream.read(buffer);
                while (i != -1){
                    os.write(buffer,0,i);
                    i = bufferedInputStream.read(buffer);
                }
                System.out.println("文件下载成功");
            }catch (IOException e){
                System.out.println("文件下载失败");
            } finally {
                if (bufferedInputStream != null){
                    try {
                        bufferedInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;

        }

    @Override
    public int deleteMusic(SysMusic sysMusic) {
        MusicMusicLisit musicMusicLisit = new MusicMusicLisit();
        SysMusic sysMusic1 = new SysMusic();
        sysMusic1.setMusic_id(sysMusic.getMusic_id());
        musicMusicLisit.setMusic_id(sysMusic.getMusic_id());
        musicMusicLisitMapper.deleteMusicMusicLisit(musicMusicLisit);

//        System.out.println(musicMapper.deleteMusic(sysMusic1));
        if (musicMapper.deleteMusic(sysMusic1)>0){
            return 1;
        }else {
            return -1;
        }
    }

    @Override
    public List<SysMusic> selectMusicByLike(String musicName) {
        return musicMapper.selectMusicByLike(musicName);
    }

    @Override
    public int selectMusicCount(String music_type) {
        return musicMapper.selectMusicCount(music_type);
    }

    @Override
    public int getMusicCount() {
        return musicMapper.getMusicCount();
    }

    @Override
    public int updataMusic(SysMusic sysMusic) {
        return musicMapper.updataMusic(sysMusic);
    }
}
